<?php

namespace App\Http\Controllers\User;

use Illuminate\Http\Request;

use App\Http\Controllers\Controller;

use Illuminate\Support\Facades\Auth;

use Illuminate\Support\Facades\DB;

class BannerController extends Controller
{

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth:web');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {

        $start_day =date('Y-m-01', strtotime(date("Y-m-d")));
        $end_day = date('d', strtotime("$start_day +1 month -1 day"));

        //查询横幅期号
        $banner = DB::table('banner')
            ->select('id', 'issue', 'date_issue', 'price', 'buy_time', 'buyer')
            ->where('issue','<=', intval($end_day))
            ->get();

        return view('user.banner.index',[
            'banner' => $banner
            ]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {

        //验证表单
        $this->validate($request, [
            'issue' => ['required','max:3'],
            'date_issue' => ['required','string','max:8'],
        ]);

        //检测是否设置了广告位
        $imageExists = DB::table('banner_image')
            ->where('set_people', Auth::user()->username)
            ->exists();

        if( !$imageExists ){
            return response()->json(['message'=>'The given data was invalid.','errors' => ['image' => ['请先设置横幅图片再来购买。']]], 422);
        }

        //检测广告位是否被购买
        $issueExists = DB::table('banner')
            ->where('date_issue', $request->date_issue)
            ->exists();

        if( $issueExists ){
            return response()->json(['message'=>'The given data was invalid.','errors' => ['periodical' => ['该期广告已被其他人购买。']]], 422);
        }

        //查询广告价格
        $price = DB::table('banner')
            ->select('id', 'issue', 'price')
            ->where('issue', (int)$request->issue)
            ->first();

        //检测账户余额
        if ($price->price > Auth::user()->money) {
            return response()->json(['message'=>'The given data was invalid.','errors' => ['money' => ['账户余额不足。']]], 422);
        } else {
            //扣除账户金额
            DB::table('users')
                ->where('id', Auth::id())
                ->decrement('money', $price->price);

            //更新购买成功到数据库
            DB::table('banner')
                ->where('issue', (int)$request->issue)
                ->update([
                    'date_issue' => $request->date_issue,
                    'buy_time' => date('Y-m-d H:i:s'),
                    'buyer' => Auth::user()->username,
                ]);

            //写入记录
            DB::table('banner_record')->insert([
                'issue' => $request->issue,
                'date_issue' => $request->date_issue,
                'consume' => $price->price,
                'buy_time' => date('Y-m-d H:i:s'),
                'buyer' => Auth::user()->username
            ]);

            return response()->json(['message' => '购买成功。', 'success' => 'true']);

        }
    }

    /**
     * banner img view.
     *
     * @return \Illuminate\Http\Response
     */
    public function record()
    {
        //查询用户购买记录
        $userRecord = DB::table('banner_record')
            ->select('id', 'issue', 'date_issue', 'consume','buy_time')
            ->where('buyer', Auth::user()->username)
            ->where(function ($query) {
                $query->orWhere('date_issue', 'like', '%'.@$_GET['search'].'%');
                $query->orWhere('buy_time', 'like', '%'.@$_GET['search'].'%');
            })
            ->orderBy('id', 'desc')
            ->paginate(17)
            ->withPath('?search=' . @$_GET['search'] . '');

        return view('user.banner.record',[
            'userRecord' => $userRecord
        ]);
    }

    /**
     * banner img view.
     *
     * @return \Illuminate\Http\Response
     */
    public function image()
    {
        //检测横幅设置是否存在
        $image = DB::table('banner_image')
            ->select('id', 'image', 'url', 'set_time')
            ->where('set_people', Auth::user()->username)
            ->first();

        return view('user.banner.image',['image'=>$image]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function image_store(Request $request){

        //验证表单
        $this->validate($request, [
            'image' => ['required','string','max:100'],
            'url' => ['required','string','max:100'],
        ]);

        DB::table('banner_image')
            ->updateOrInsert(
                ['set_people' => Auth::user()->username],
                [
                    'image' => $request->image,
                    'url' => $request->url,
                    'set_time' => date('Y-m-d H:i:s'),
                    'set_people' => Auth::user()->username
                ]
            );

        return response()->json(['message' => '设置成功。', 'success' => 'true']);

    }
}
